class GamePlay extends eui.UILayer {

    penguin : any;
    bear : any;
    knockPoint : any;
    penguinWidth : any;
    penguinHeight : any;
    bearHeight : any;
    floorLine = Const.SCENT_HEIGHT - 80;
    tracewidth = 70;
    backGroundImg : any;
    // 角度
    minAngle = 5;
    maxAngle = 45;
    randomAngle = 2; // 上下偏移角度
    // 路标
    guideWidth : number;
    guideHeight : number;
    guideText : any;    
    guide : any;
    broadtip:any;

    // 距离标识
    gameOverScore : any;
    gameOverScoreBg : any;
    gameOverScoreText : any;

    // 提示
    gametips : any;

    // 击飞角度
    angle : number;

    reset : any;

    visibleDistance = 250;
    penguinOffsetX = 295;

    // 企鹅的掉落动作
    penguinAnimation : any;
    penguintimer : any;
    beartimer : any;
    penguinmask : any;

    againbutton : any;
    flyobject : any;
    scoretext : any;
    score = 0;

    moveStage = this.moveStage1;

    noshoottrace : any;
    endTrace: any;

    diesound: any;
    diesoundchanel:any;

    gamesound: any;
    gamesoundchanel:any;

    public constructor() {
        super();
        this.createView();
        this.creatediesound();
    }

    private createView(): void{
        let stageW = Const.SCENT_WIDTH
        let stageH = Const.SCENT_HEIGHT

        this.reset = new GameReset(this);

        // 背景
        let img = new egret.DisplayObjectContainer();        
        let sky = Common.createBitmapByName("scenebg2_png");
        img.addChild(sky);
        sky = Common.createBitmapByName("scenebg2_png");
        img.addChild(sky);
        sky.x = stageW
        sky = Common.createBitmapByName("scenebg1_png");
        img.addChild(sky);
        sky.x = stageW * 2

        this.backGroundImg = img;
        this.addChild(img);
        this.reset.background();

        // 初始化
        this.penguin = new MoveClipSpriteSheet("jjjump_json",7,false);
        let jumpbitmap = Common.createBitmapByName("jjjump_png");
        this.penguinWidth = 93;
        this.penguinHeight = jumpbitmap.getBounds().height;
        this.addChild(this.penguin);

        this.bear = new MoveClipSpriteSheet("dog_json",8,false);
        this.bearHeight = Common.createBitmapByName("dog_png").getBounds().height;
        this.addChild(this.bear);

        // 距离标记
        let guideBg = Common.createBitmapByName("guide_png");
        let guideBgH = guideBg.getBounds().height;
        let guideBgW = guideBg.getBounds().width;
        let guideIcon = new egret.DisplayObjectContainer();
        guideIcon.addChild(guideBg);
        guideIcon.y = this.floorLine - guideBgH - 200;
        let guidText = new egret.TextField()
        guidText.text = "你好啊,小傻瓜"
        guidText.size = 40;
        guidText.textColor = 0x2B5580;
        guidText.y = 50;
        guidText.width = guideBgH + 40;
        guidText.textAlign = egret.HorizontalAlign.CENTER;
        guideIcon.addChild(guidText);
        this.guideWidth = guideBgW;
        this.guideHeight = guideBgH;
        this.guideText = guidText;
        this.guide = guideIcon;
        //this.addChild(guideIcon);
        this.reset.guide("100M");

        // 得分
        this.gameOverScore = new egret.DisplayObjectContainer();
        this.gameOverScore.x = 10;
	    this.gameOverScore.y = 10;
        this.addChild(this.gameOverScore);

        this.scoretext = new egret.TextField();
        this.scoretext.textColor = 0xff0000;
        this.scoretext.size = 36;
        this.scoretext.text = "得分：0";
        this.gameOverScore.addChild(this.scoretext);

        // 提示
        this.gametips = new egret.DisplayObjectContainer();
        let top = new egret.TextField();
        top.textColor = 0x336600;
        top.size = 36;
        top.text = "点击开始";
        this.gametips.addChild(top);
        let text = new egret.TextField();
        text.textColor = 0xFF0000;
        text.size = 36;
        text.y = 36;
        text.text = "再次点击挥棒";
        this.gametips.addChild(text);
        this.addChild(this.gametips);

        // 再來一次按鈕
        let button_icon = Common.createBitmapByName("jjagain_png")
        this.againbutton = new eui.Button();
        //this.againbutton.horizontalCenter = 0;
        //this.againbutton.verticalCenter = 0;
        this.againbutton.icon = button_icon.texture;
        this.againbutton.x = Const.SCENT_WIDTH/2 -260;
        this.againbutton.y = Const.SCENT_HEIGHT - 100;
        this.againbutton.width = 50;
        this.againbutton.height = 20;
        this.againbutton.scaleX = 0.6
         this.againbutton.scaleY = 0.6
        this.addChild(this.againbutton);
        this.againbutton.visible = false;
        this.againbutton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onAgainClick, this);

         //标示牌 
        this.broadtip = new egret.DisplayObjectContainer();
        let broadbg = Common.createBitmapByName("guanggao_png")
        this.broadtip.x = Const.SCENT_WIDTH/2 -350;
        this.broadtip.y = Const.SCENT_HEIGHT- 380;
        this.broadtip.addChild(broadbg);

        let bbtop = new egret.TextField();
        bbtop.textColor = 0xFF0000;
        bbtop.size = 26;
        bbtop.text = "大吉大利";
        bbtop.x =54;
        bbtop.y =90;
        this.broadtip.addChild(bbtop);
        let bbtext = new egret.TextField();
        bbtext.textColor = 0xFF0000;
        bbtext.size = 26;
        bbtext.x = 54
        bbtext.y = 114
        bbtext.text = "今年吃鸡";
        this.broadtip.addChild(bbtext);
        this.addChild(this.broadtip);

        // 一些初始化位置等信息放这里
        this.reset.init();

        this.knockPoint = Math.ceil(this.bear.y + this.bearHeight / 2)
        console.log("打击点" + this.knockPoint)

        var timer:egret.Timer = new egret.Timer(200,1);
        timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE,this.initEvent,this);
        timer.start();
        /*if(DEBUG){
            var shape = new egret.Shape();
            shape.graphics.beginFill(0xff0000);
            shape.graphics.drawRect(0,0,40,40);		
            shape.x = this.bear.x - 20;
            shape.y = this.knockPoint - 20;
            shape.graphics.endFill();
            this.addChild(shape);

            var floor = new egret.Shape();
            floor.graphics.beginFill(0xff0000)
            floor.graphics.drawRect(0,0,Const.SCENT_WIDTH,10);		
            floor.x = 0;
            floor.y = this.floorLine;
            this.addChild(floor);
        }*/
    }

    private initEvent()
    {
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, function(event){
            this.touchscreen()
        },this);

        this.addEventListener(GameOver.OVER,function(evt:GameOver){
            //console.log("gameOver = "+evt.distance);
            if(this.againbutton)
                this.againbutton.visible = true;
            if(this.diesound )
                this.diesoundchanel = this.diesound.play(0,1);
            if(this.gamesoundchanel)
                this.gamesoundchanel.stop();  

        },this);

        this.addEventListener(StageMove.Move, this.moveStage,this);
        this.addEventListener(StageMove.Stop, function(evt:StageMove){

        },this);
    }

    private moveStage1 (evt)
    {
        this.moveStage = this.moveStage2
        this.moveStage(evt)
    }
    private moveStage2 (evt)
    {
        let distance = evt.distance
        let totaldis = evt.totalDistance
        if(this.backGroundImg.x < -Const.SCENT_WIDTH){
            this.backGroundImg.x += distance;
            this.gametips.x += distance;
            this.bear.x += distance;
            this.broadtip.x += distance;

	        this.moveGuide(evt.distance, evt.totalDistance);
        }
        else
        {
            this.moveStage = this.moveStage3         
            this.moveStage(evt)
        }
    }
    private moveStage3 (evt)
    {
        this.backGroundImg.x += evt.distance
        if(this.backGroundImg.x >= 0)
        {
            this.backGroundImg.x -= this.width
        }
	    this.moveGuide(evt.distance, evt.totalDistance);
    }
    
    private stopMove ()
    {
        this.moveStage = this.moveStage1;
    }

    guideMoveLength = 0;
    guideMoveIndex = 1;
    private moveGuide(dis,totaldis){
        this.guide.x += dis;
        // 路标
        this.guideMoveLength += dis;
        if(this.guideMoveLength >= this.guideDistance + this.guideWidth){
            this.reset.guide(++this.guideMoveIndex + "00M");
            this.guideMoveLength = 0;
        }
    }

    // 路标间距
    guideDistance = Const.SCENT_WIDTH / 2; 
    private getTotalDistance(distance:number):number{        
        let result = this.guideMoveIndex * 100;
        let total = this.guideDistance + this.guideWidth
        result += Math.round(this.guide.x * total / Const.SCENT_WIDTH) / 10;        
        console.log(distance + " result = "+result)
        return distance > 0 ? result : 0;
    }

    isPlaying = false;// 正在进行游戏
    isQuiver = false; // 是否击中
    canShoot = true;

    private touchscreen(){
        if(this.canShoot == false)
            return;
        if(!this.isPlaying){
            this.isPlaying = true;

            console.log("企鹅跳")
            // 播个序列帧动画 先用定时器做
            if(this.penguintimer == null)
            {
                this.penguintimer = new egret.Timer(20);
                this.penguintimer.addEventListener(egret.TimerEvent.TIMER, this.playpenguinAni, this);
            }
            this.penguintimer.start();
        
            // 向下跳
            var toY = this.floorLine - this.penguinHeight/2;
            this.penguinAnimation = egret.Tween.get(this.penguin);
            this.penguinAnimation.to({y:toY},1100,egret.Ease.quadIn)
            .call(function(){
                var event = new GameOver(GameOver.OVER)
                event.distance = 0;
                this.dispatchEvent(event);

                // 雪坑
                this.onNoShootEnd();
                //console.log("游戏结束");
            },this)

            // 第二次挥棒 
        }else {
            var timer:egret.Timer = new egret.Timer(300,1);
            timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE,this.bearShoot,this);
            timer.start();
            if(this.beartimer == null)
            {
                this.beartimer = new egret.Timer(120);
                this.beartimer.addEventListener(egret.TimerEvent.TIMER, this.playbearAni, this);
            }
            this.beartimer.start();
            this.canShoot = false;
        }
    }

    private bearShoot(){
        //console.log("企鹅位置："+this.penguin.y);
        var penguinY = this.penguin.y;
        var clickY = penguinY + this.penguinHeight - this.knockPoint;
        this.isQuiver = (clickY >= -20 && clickY <= this.penguinHeight-20);
        if(this.isQuiver){
		clickY = Math.ceil(clickY / this.penguinHeight * 100);
		this.angle = this.calculateAngle(clickY);
		console.log("击中角度:" + this.angle);
        this.penguin.visible = false
        this.flyobject = new FlyLine()
        this.flyobject.setGameScene(this)
        this.addChild(this.flyobject)
        this.penguinAnimation.setPaused(true);
        }
        else
        {
            console.log("你木有击中！！");
        }
    }

    private playpenguinAni()
    {
        if(this.penguin.y >= this.floorLine - this.penguinHeight)
        {
            this.penguin.mask = this.penguinmask;
        }
        this.penguin.render(40);
    }

    private playbearAni()
    {
         this.bear.render(240);
    }

    private calculateAngle (x){
        console.log("角度" + x);
        var y = this.minAngle + this.maxAngle * Math.sin(Math.PI * x / 200);
        y += Math.round(Math.random() * this.randomAngle) * (Math.random() < 0.5 ? -1 : 1);
        return Math.ceil(y);
    }

    private onNoShootEnd(){
        this.noshoottrace = Common.createBitmapByName("traces_png");
        this.noshoottrace.x = this.penguin.x + this.penguinWidth/2 - this.tracewidth/2 - 10;
        this.noshoottrace.y = this.floorLine - 7;
        this.noshoottrace.width = this.tracewidth;
        this.addChild(this.noshoottrace);
        this.swapChildren(this.penguin,this.noshoottrace)
        this.canShoot = false
    }

    private onShootEnd(fx:number,fy:number){
        this.penguin.visible = false;
        this.endTrace = new MoveClipSpriteSheet("jjflyend_json",2, false);
		this.endTrace.gotoAndPlay(1);
		this.endTrace.x = fx;
		this.endTrace.y = this.floorLine - this.penguinHeight/2;
        this.addChild(this.endTrace);
        this.canShoot = false
    }
    /**
     * 点击按钮
     * Click the button
     */
    private onButtonClick(e: egret.TouchEvent) {
        let panel = new eui.Panel();
        panel.title = "Title";
        panel.horizontalCenter = 0;
        panel.verticalCenter = 0;
        this.addChild(panel);
    }

    private onAgainClick(e: egret.TouchEvent) {
        this.againbutton.visible = false;
        this.reset.replay();
        if(this.diesoundchanel)
            this.diesoundchanel.stop();
        if(this.gamesound)
            this.gamesoundchanel = this.gamesound.play(0,1);
    }

    private creatediesound():void{  
        this.diesound = new egret.Sound();
        var url:string = "resource/assets/die.mp3";
        this.diesound.load(url);

        this.gamesound = new egret.Sound();
        var url:string = "resource/assets/bgm.mp3";
        this.gamesound.load(url);
        this.gamesound.addEventListener(egret.Event.COMPLETE, this.onLoadComplete, this);
        
    }
    private onLoadComplete(event:egret.Event):void {
        var sound:egret.Sound = <egret.Sound>event.target;
        this.gamesoundchanel = sound.play(0,1);
    }
    
}
